﻿using HybridLab.Virtual.Interfaces;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Management;

namespace HybridLab.Virtual.HyperV
{
	[Export(typeof(IVirtualHost))]
	public class HyperVHost : HostBase
	{
		public override string HostType
		{
			get
			{
				return "HyperV";
			}
		}

		public ManagementObject VMManagementService { get; private set; }

		private ConnectionOptions connectionOptions;

		public ManagementScope RootScope { get; private set; }

		public override void Connect(string hostName, string domain, string userName, string password)
		{
			base.Connect(hostName, domain, userName, password);

			if (hostName.ToLower() == "localhost")
			{
				connectionOptions = null;
				hostName = ".";
			}
			else
			{
				connectionOptions = new ConnectionOptions()
				{
					Username = userName,
					Password = password
				};
				if (!string.IsNullOrEmpty(domain))
				{
					connectionOptions.Authority = "ntlmdomain:" + domain;
				}
			}
			string connectionRoot = string.Format(@"\\{0}\root\virtualization\v2", hostName);
			RootScope = new ManagementScope(connectionRoot, connectionOptions);

			VMManagementService = HyperVUtils.GetHyperVManagementService(RootScope);
		}

		public override List<IVirtualMachine> GetVMs()
		{
			var list = HyperVUtils.GetWmiObjects(RootScope, HyperVUtils.VirtualMachineClass);
			var vms = from o in list
					  where o["Caption"].ToString() == "Virtual Machine"
					  select new HyperVVirtualMachine(o, this);
			return vms.Cast<IVirtualMachine>().ToList();
		}
	}
}
